package com.jeeplus.test.jlnu.archivalInfo.service.impl;

import com.jeeplus.sys.domain.DictValue;
import com.jeeplus.sys.service.DictValueService;
import com.jeeplus.sys.service.dto.DictValueDTO;
import com.jeeplus.sys.service.mapstruct.DictValueWrapper;
import com.jeeplus.test.jlnu.admissionInfo.mapper.AdmissionInfoMapper;
import com.jeeplus.test.jlnu.admissionInfo.utils.MyWebSocketHandler;
import com.jeeplus.test.jlnu.archivalInfo.domain.vo.ArchivalInfoExcelVO;
import com.jeeplus.test.jlnu.archivalInfo.mapper.ArchivalInfoMapper;
import com.jeeplus.test.jlnu.changeStuInfo.domain.entity.ChangeStuInfo;
import com.jeeplus.test.jlnu.changeStuInfo.mapper.ChangeStuInfoDetailMapper;
import com.jeeplus.test.jlnu.changeStuInfo.mapper.ChangeStuInfoMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.jeeplus.test.jlnu.archivalInfo.service.ExcelArcService;

import javax.annotation.Resource;


@Service
public class ExcelArcServiceimpl implements ExcelArcService {

    @Autowired
    private ArchivalInfoMapper archivalInfoMapper;

    @Autowired
    private MyWebSocketHandler webSocketHandler;

    @Autowired
    private AdmissionInfoMapper admissionInfoMapper;

    @Autowired
    private DictValueService dictValueService;

    @Autowired
    private DictValueWrapper dictValueWrapper;

    @Autowired
    private ChangeStuInfoMapper changeStuInfoMapper;

    @Autowired
    private ChangeStuInfoDetailMapper changeStuInfoDetailMapper;



    String[] materialOptions;
    String[] materialOptionsCop;

    @Override
    public void insertDataArch(List<ArchivalInfoExcelVO> dataList) {
        try {
            if (CollectionUtils.isEmpty(dataList)) {
                return;
            }
            //去除重复元素，根据StudentId
            List<ArchivalInfoExcelVO> newDataList = new ArrayList<>();
            List<String> errorList = new ArrayList();

            materialOptions = getMaterialOptions("1898906530877710338");
            materialOptionsCop = Arrays.copyOf(materialOptions, materialOptions.length);
             ;for (int i = 0; i < materialOptionsCop.length; i++) {
                // 按中文冒号分割，取后半部分
                materialOptionsCop[i] = materialOptionsCop[i].split("：")[1];
            }
            dataList.forEach(e -> {
                String xh = e.getStudentId();
                String materialSort = e.getMaterialSort();
                String dateTime = e.getDateTime();
                int count = admissionInfoMapper.checkStudentId(xh);
                if (StringUtils.isEmpty(xh)) {
                    String msg = "姓名：("+e.getName()+")学号为空请输入学号！";
                    errorList.add(msg);
                } else if(!StringUtils.isEmpty(xh) && count < 1){
                    String msg = "姓名：（"+e.getName()+"）学号不存在";
                    //向数据库中添加失败数据
                    e.setStatus("2");
                    e.setFailMsg("学号不存在");
                    errorList.add(msg);
                    e.setMaterialSort(convert(e.getMaterialSort()));
                    newDataList.add(e);
                } else if(StringUtils.isEmpty(materialSort)){
                    String msg = "姓名：（"+e.getName()+"）未填写材料类别";
                    errorList.add(msg);
                } else if(convert(e.getMaterialSort()).equals("-1")){
                    String msg = "姓名：（"+e.getName()+"）无效的档案信息";
                    errorList.add(msg);
                } else if(StringUtils.isEmpty(dateTime)){
                    String msg = "姓名：（"+e.getName()+"）未填写文件日期";
                    errorList.add(msg);
                }else {
                    e.setMaterialSort(convert(e.getMaterialSort()));
                    e.setStatus("1");
                    e.setApproveState("1");
                    newDataList.add(e);
                }
            });
            if (!CollectionUtils.isEmpty(errorList)) {
                sendMsg(errorList);
            }

            if(dataList.isEmpty() || dataList.size() > 0){
                final String officeType=changeStuInfoDetailMapper.getTypeById(dataList.get(0).getOfficeId());
                List<ChangeStuInfo> changeStuInfos = dataList.stream()
                    .map(e -> {
                        ChangeStuInfo csi = new ChangeStuInfo();
                        csi.setStudentId(e.getStudentId());
                        csi.setOfficeId(e.getOfficeId());
                        csi.setSource(officeType);
                        csi.setCreateTime(new Date());
                        csi.setKsh(e.getCandidateNumber());
                        csi.setName(e.getName());
                        csi.setGender(e.getGender());
                        csi.setCollegeName(e.getCollegeName());
                        csi.setMajorName(e.getMajorName());
                        csi.setGrade(e.getGrade());
                        csi.setClassId(e.getClassId());
                        csi.setExamTicketNumber(e.getAdmissionTicketNumber());
                        csi.setEthnicity(e.getEthnicity());
                        csi.setIdCardNumber(e.getIdNumber());
                        csi.setStudentSource(e.getOriginPlace());
                        csi.setRecordDate(e.getDateTime());
                        csi.setSpecification(e.getStandards());
                        csi.setCopies(e.getQuantity());
                        csi.setPages(e.getPageCount());
                        csi.setArchiveUnit(e.getArchiveUnit());
                        csi.setTransferPerson(e.getTransferor());
                        csi.setReceiver(e.getReceiver());
                        csi.setTransferTime(e.getTransferTime());
                        csi.setArchiveNumber(e.getArchiveNumber());
                        csi.setCaseTitle(e.getCaseTitle());
                        csi.setDocumentTitle(e.getFileTitle());
                        csi.setPageLocation(e.getPageNumber());

                        return csi; // 返回生成的 AdmissionInfo 对象
                    }).collect(Collectors.toList());// 收集到 admissionInfos 列表中
                changeStuInfoMapper.insertChangeStu(changeStuInfos);//学籍管理循环插入
            }

            archivalInfoMapper.addDataArch(newDataList);

        } catch (Exception e) {

            System.out.println(e.getMessage());
            //("数据异常，请联系管理员");
            sendMsg("数据异常，请联系管理员");
        }


    }

    private void sendMsg(List<String> msg) {
        try {
            //
            webSocketHandler.sendMsgList(msg);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    private void sendMsg(String msg) {
        try {
            //
            webSocketHandler.sendMsg(msg);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }



    // 动态加载字典数据的方法
    private String[] getMaterialOptions(String dictTypeId) {
        List<DictValueDTO> dictValues =  dictValueService.lambdaQuery ( ).eq ( DictValue::getDictTypeId, dictTypeId ).orderByAsc ( DictValue::getSort ).list ( ).stream ( ).map ( dictValueWrapper::toDTO ).collect ( Collectors.toList ( ) );
        return dictValues.stream()
                .map(dv -> dv.getValue() + "：" + dv.getLabel())
                .toArray(String[]::new);
    }

    private String convert(String type) {
        for (String option : materialOptions) {
            int colonIndex = option.indexOf("：");
            if (colonIndex != -1) {
                String key = option.substring(0, colonIndex);
                String value = option.substring(colonIndex + 1);

                if (value.equals(type)) {
                    return key;
                }
            }
        }
        return "-1";
    }
}
